<?php
defined('BASEPATH') OR exit('No direct script access allowed');

// 公共类不用校验权限
class Pub extends BaseController {
    public function __construct() {
        parent::__construct();

        // 班牌手机端静态页面
        $this->staticWxUrl = $this->staticUrl . WX_DIR . "/";
        // 获取缓存数据
        $this->wxSession = $this->session->userdata('wx');
        
        // 加载库
        $this->load->model('schoolModel');
        $this->load->model('wxUserModel');
        $this->load->model('dataModel');
    }

    /*
     * 绑定账号页面
    */
    public function bind_card() {
        $this->htmlTitle = '绑定账号';
        // 获取学校所有地区
        $this->load->library('area');
        $this->citys = $this->area->get_school_areas_to_city();
        // 判断是否已经授权
        if(!isset($this->wxSession['openid'])) {
            // 未登录就跳到授权页面
            $this->load->library('wechat');
            $this->wechat->authorize();
        }
        $this->display(WX_DIR . DIRECTORY_SEPARATOR . 'bind_card');
    }

    // 获取某地区的学校
    public function get_area_schools() {
        $cityCode = $this->get('cityCode');
        if($cityCode) {
            $params['cityCode'] = $cityCode;
        }
        $schools = $this->schoolModel->get_school_list($params);
        exit(json('', true, $schools));
    }

    // 绑定账号操作
    public function bind_card_action() {
        $schoolId = $this->post('schoolId');
        $username = trim($this->post('username'));
        $password = trim($this->post('password'));
        $realname = trim($this->post('realname'));
        if(empty($schoolId)) {
            throw new Exception('请选择学校');
        }
        if(empty($username)) {
            throw new Exception('账号不能为空');
        }
        if(empty($password)) {
            throw new Exception('密码不能为空');
        }
        if(empty($realname)) {
            throw new Exception('姓名不能为空');
        }
        $params['isDelete'] = 0;
        // 支持绑定管理员
        $params['allUserType'] = 1;
        $params['schoolId'] = $schoolId;
        $params['username'] = $username;
        $params['realname'] = $realname;
        // 获取学生
        $students = $this->schoolModel->get_student_list($params);
        // 获取教师
        $teachers = $this->schoolModel->get_teacher_list($params);
        if(empty($students) && empty($teachers)) {
            throw new Exception('账号姓名错误');
        }
        // 绑定学生
        if(!empty($students)) {
            $student = $students[0];
            // 验证密码
            if(!password_verify($password, $student['password'])) {
                throw new Exception('账号密码错误');
            }
            // 绑定成功
            $this->_bind_success($student, BIND_TYPE_STUDENT);
            exit(json('绑定成功', true));
        }

        // 绑定教师
        $teacher = $teachers[0];
        // 存在两个相同账号，优先学校管理员
        if(count($teachers) > 1) {
            foreach($teachers as $v) {
                if($v['user_type'] == USER_TYPE_SCHOOL) {
                    $teacher = $v;
                }
            }
        }
        // var_export($teacher);exit;
        // 验证密码
        if(!password_verify($password, $teacher['password'])) {
            throw new Exception('账号密码错误');
        }
        // 绑定成功
        $this->_bind_success($teacher, BIND_TYPE_TEACHER);
        exit(json('绑定成功', true));
    }

    // 绑定成功
    private function _bind_success($user, $bindUserType) {
        // 入库
        // 判断wx_user是否存在
        $openid = $this->wxSession['openid'];
        $wxUser = $this->wxUserModel->get_wx_user_by_openid($openid);

        // var_export($openid);exit;
        if($wxUser) {
            // wx_user已存在
            $wxUserId = $wxUser['id'];
        } else {
            // 获取微信用户信息
            $this->load->library('wechat');
            $wxUserInfo = $this->wechat->get_user_info($openid);
            // 创建wx_user
            $data = array(
                'openid' => $openid,
                'nickname' => urlencode($wxUserInfo['nickname']),
                'headimgurl' => $wxUserInfo['headimgurl'],
                'sex' => isset($wxUserInfo['sex']) ? $wxUserInfo['sex'] : 1,
                'createtime' => date('Y-m-d H:i:s')
            );
            $this->db->insert(WxUserModel::$wxUserTable, $data);
            $wxUserId = $this->db->insert_id();
        }
        if(empty($wxUserId)) {
            throw new Exception('服务异常，请重试');
        }
        // 判断是否已绑定
        $params['wxUserId'] = $wxUserId;
        $params['bindUserId'] = $user['id'];
        $params['bindUserType'] = $bindUserType;
        $params['isDelete'] = 0;
        $bind = $this->wxUserModel->get_bind_user_list($params);
        if($bind) {
            throw new Exception('已绑定过该账号');
        }
        // 创建wx_user_bind
        $data = array(
            'wx_user_id' => $wxUserId,
            'bind_user_id' => $user['id'],
            'bind_user_type' => $bindUserType,
            'is_delete' => 0,
            'createtime' => date('Y-m-d H:i:s'),
            'updatetime' => date('Y-m-d H:i:s')
        );
        $this->db->insert(WxUserModel::$wxUserBindTable, $data);
        // 设置用户session
        if(empty($this->wxSession)) {
            $sessArr = array(
                'user' => $user,
                'bind_user_type' => $bindUserType
            );
        } else {
            $sessArr = array_merge($this->wxSession, array(
                'user' => $user,
                'bind_user_type' => $bindUserType
            ));
        }
        $this->session->set_userdata('wx', $sessArr);
    }

    /*
     * 选择账号页面
    */
    public function card() {
        $this->htmlTitle = '选择账号';
        // 获取wx_user
        $wxUser = $this->wxUserModel->get_wx_user_by_openid($this->wxSession['openid']);
        if(empty($wxUser)) {
            // 跳转绑定账号
            header('Location: ' . wx_url('pub/bind_card'));
        }
        // 获取学校列表
        $schoolList = $this->schoolModel->get_school_list();
        $schoolList = array_value_to_key($schoolList, 'id');
        // 获取已绑定的所有账号
        $params['orderBy'] = '`bind_user_type` DESC';
        $params['isDelete'] = 0;
        $params['wxUserId'] = $wxUser['id'];
        $bindUsers = $this->wxUserModel->get_bind_user_list($params);
        foreach($bindUsers as $key => &$bindUser) {
            // 获取用户详情信息
            if($bindUser['bind_user_type'] == BIND_TYPE_STUDENT) {
                // 设置用户角色
                $bindUser['role'] = '学生';
                // 学生信息
                $user = $this->schoolModel->get_student_info($bindUser['bind_user_id']);
            } else {
                // 设置用户角色
                $bindUser['role'] = '教师';
                // 教师信息
                $user = $this->schoolModel->get_school_user_info_realname($bindUser['bind_user_id']);
                // 判断是否为管理员
                if($user['user_type'] == USER_TYPE_SCHOOL) {
                    $bindUser['role'] = '管理员';
                }
            }
            // 排除管理员
            // if($user['is_delete'] == 1 || (isset($user['user_type']) && $user['user_type'] == USER_TYPE_SCHOOL)) {
            // 支持管理员登录    
            if(empty($user) || $user['is_delete'] == 1 || ($bindUser['role'] == '学生' && $user['is_graduated'] == 1)) {
                //判断是否已删除或已毕业
                unset($bindUsers[$key]);              
            } else {
                // 设置用户信息
                $bindUser['realname'] = $user['realname'] ? $user['realname'] : $user['username'];
                $bindUser['headimgurl'] = $user['headimgurl'];
                // 获取学校名称
                if(isset($schoolList[$user['school_id']])) {
                    $schoolname = $schoolList[$user['school_id']]['school_name'];
                    $bindUser['role'] = $bindUser['role'] . ' - ' . $schoolname;
                }
            }
        }
        // 过滤重复值
        $bindUsers = array_unique_by_key($bindUsers, 'id');
        $this->bindUsers = $bindUsers;
        $this->display(WX_DIR . DIRECTORY_SEPARATOR . 'card');
    }

    // 选择账号操作
    public function choose_card() {
        $userId = $this->post('user_id');
        $bindUserType = $this->post('bind_user_type');
        // 获取绑定的用户
        if($bindUserType == BIND_TYPE_STUDENT) {
            // 获取学生
            $user = $this->schoolModel->get_student_info($userId);
        } else {
            // 获取教师
            $user = $this->schoolModel->get_school_user_info_realname($userId);
        }
        // session设置登录的user
        if(empty($this->wxSession)) {
            $sessArr = array(
                'user' => $user,
                'bind_user_type' => $bindUserType
            );
        } else {
            $sessArr = array_merge($this->wxSession, array(
                'user' => $user,
                'bind_user_type' => $bindUserType
            ));
        }
        $this->session->set_userdata('wx', $sessArr);
        exit(json('', true));
    }

    /*
     * 签到详情页面
    */
    public function student_sign_detail($signId) {
        $this->htmlTitle = '签到详情';
        // 获取签到详情
        $this->signInfo = $this->dataModel->get_sign_data_detail($signId);
        $this->signInfo['sign_type'] = transform_sign_type($this->signInfo['sign_type']);

        // 获取学生信息
        $studentId = $this->signInfo['student_id'];
        $studentInfo = $this->schoolModel->get_student_info($studentId);
        $this->signInfo['studentInfo'] = $studentInfo;

        // 处理温度
        $this->signInfo['temperature'] = handle_temperature($this->signInfo['temperature']);

        // 获取jssdk参数
        $this->load->library('wechat');
        $url = substr(BASE_URL, 0 , -1) . $_SERVER['REQUEST_URI'];
        $this->dataJssdk = $this->wechat->jssdk_data($url);
        $this->display(WX_DIR . DIRECTORY_SEPARATOR . 'student_sign_detail');
    }

    /*
     * 模板消息对话留言跳转
    */
    public function note_dialog() {
        $sendUserId = $this->get('send_user_id');
        // $sendUserType = $this->get('send_user_type');
        $receiveUserId = $this->get('receive_user_id');
        $receiveUserType = $this->get('receive_user_type');
        $isBrand = $this->get('is_brand');
        // 自动登录接收用户
        if($receiveUserType == BIND_TYPE_STUDENT) {
            // 获取学生
            $user = $this->schoolModel->get_student_info($receiveUserId);
        } else {
            // 获取教师
            $user = $this->schoolModel->get_school_user_info_realname($receiveUserId);
        }
        $this->bindUserType = $receiveUserType;
        $this->user = $user;
        // session设置登录的user
        $wxSession = $this->session->userdata('wx');
        // 如果当前不是登陆对话用户，才自动登录
        if(empty($wxSession) || !isset($wxSession['bind_user_type']) || !isset($wxSession['user']['id']) || $wxSession['bind_user_type'] != $receiveUserType || $wxSession['user']['id'] != $user['id']) {
            if(empty($wxSession)) {
                $sessArr = array(
                    'user' => $user,
                    'bind_user_type' => $receiveUserType
                );
            } else {
                $sessArr = array_merge($this->wxSession, array(
                    'user' => $user,
                    'bind_user_type' => $receiveUserType
                ));
            }
            $this->session->set_userdata('wx', $sessArr);
        }


        // 跳转到对话留言页面
        if($isBrand) {
            if($receiveUserType == BIND_TYPE_STUDENT) {
               // 家长与学生对话
               $url = wx_url('classes/brand_note');
            } else {
               // 老师与学生对话
               $url = wx_url('classes/brand_note_dialog/' . $sendUserId);
            }
        } else {
            // 家长与老师对话
            $url = wx_url('classes/note_dialog/' . $sendUserId);
        }

        header("Location: " . $url);
    }

    // 防疫详情页面
    public function health_info_check($id) {
        $this->htmlTitle = '防疫信息详情';
        $health = $this->wxUserModel->get_wx_user_health_info($id);
        // 获取其他信息
        $healthData = get_health_const_data();
        $health['current_status'] = $healthData['current_status'][$health['current_status']];
        $health['family_status'] = $healthData['family_status'][$health['family_status']];
        $health['treatment'] = $healthData['treatment'][$health['treatment']];
        $health['is_return'] = $health['is_return'] ? '是' : '否';
        $health['is_contact'] = $health['is_contact'] ? '是' : '否';
        $health['is_detained'] = $health['is_detained'] ? '是' : '否';
        $health['holiday_dest'] = $health['holiday_dest'] ? $health['holiday_dest'] : '无';
        $health['holiday_dest_desc'] = $health['holiday_dest'] ? $health['holiday_dest_desc'] : '';
        // 获取症状数组
        $symptomkeyArr = explode(',', $health['symptom']);
        // 获取症状字符数组
        $symptomArr = array();
        if($symptomkeyArr) {
            foreach($symptomkeyArr as $symptomkey) {
                if($symptomkey) {
                    array_push($symptomArr, $healthData['symptom'][$symptomkey]);
                }
            }
            $health['symptom'] = implode(',', $symptomArr);
        }
        $health['symptom'] = $health['symptom'] ? $health['symptom'] :'自觉正常';
        // 获取学生头像
        $studentInfo = $this->schoolModel->get_student_info($health['user_id']);
        $health['headimgurl'] = $studentInfo['headimgurl'];
        $this->health = $health;
        // echo '<pre>';var_export(($health));exit;
        $this->display(WX_DIR . DIRECTORY_SEPARATOR . "health_info_check");
    }

    /*
     * 视频教程页面
    */
    public function video_tutorial() {
        $this->htmlTitle = '视频教程';
        $this->display(WX_DIR . DIRECTORY_SEPARATOR . 'pub/video_tutorial');
    }

    /*
     * 扫码签到
    */
    public function scan_sign() {
        $this->htmlTitle = '扫码签到';
        $this->display(WX_DIR . DIRECTORY_SEPARATOR . 'pub/scan_sign');
    }
}